/**
 * select 实现 IO 多路复用模型
*/

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <pthread.h>

#include <arpa/inet.h>

#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/select.h>

#include "vector_fd.h"

#define PORT 9999
#define LISTEN_MAXNUM 10

VectorFD *vfd;

static int tcp_server_init()
{
    int socketfd = socket(AF_INET, SOCK_STREAM, 0);
    if (socketfd < 0)
    {
        perror("socket error: ");
        return -1;
    }

    struct sockaddr_in serverAddr;
    memset(&serverAddr, 0, sizeof(struct sockaddr_in));
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(PORT);
    serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);

    int opt = 1;
    if (setsockopt(socketfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0)
    {
        perror("setsockopt error: ");
        exit(EXIT_FAILURE);
    }

    if (bind(socketfd, (struct sockaddr *)&serverAddr, sizeof(struct sockaddr)) < 0)
    {
        perror("bind error: ");
        close(socketfd);
        return -1;
    }

    if (listen(socketfd, LISTEN_MAXNUM) < 0)
    {
        perror("listen error: ");
        close(socketfd);
        return -1;
    }

    return socketfd;
}

static void out_client_info(struct sockaddr_in clientAddr)
{
    char *ip = inet_ntoa(clientAddr.sin_addr);
    unsigned short port = ntohs(clientAddr.sin_port);
    printf("Connection from %s:%d\n", ip, port);
}

static int add_set(fd_set *readset)
{
    FD_ZERO(readset);

    int max = 0;
    int i = 0;
    for (; i < vfd->counter; ++i)
    {
        if (max < get_fd(vfd, i))
        {
            max = get_fd(vfd, i);
        }

        FD_SET(get_fd(vfd, i), readset);
    }

    return max;
}

static void do_service(int fd)
{
    char buf[1024] = {0};

    int len = read(fd, buf, 1024);
    if (0 > len)
    {
        perror("read error: ");
        exit(EXIT_FAILURE);
    }
    else if (0 == len)
    {
        printf("Client leave!\n");
        close(fd);
        remove_fd(vfd, fd);
    }
    else
    {
        printf("client msg %s\n", buf);
        write(fd, buf, len);
    }
}

void *tcp_server_pthread(void *arg)
{
    fd_set rset;
    int max_fd;
    int retval;
    struct timeval timeout;
    while (1)
    {
        timeout.tv_sec = 4;
        timeout.tv_usec = 0;

        max_fd = add_set(&rset);
        retval = select(max_fd + 1, &rset, NULL, NULL, &timeout);

        if (0 > retval)
        {
            perror("Select error: ");
            exit(EXIT_FAILURE);
        }
        if (0 < retval)
        {
            int i = 0;
            for (; i < vfd->counter; ++i)
            {
                if (FD_ISSET(get_fd(vfd, i), &rset))
                {
                    do_service(get_fd(vfd, i));
                }
            }
        }
    }
}

int main(void)
{
    int sockfd = tcp_server_init();
    if (sockfd == -1)
    {
        exit(EXIT_FAILURE);
    }

    vfd = create_vector_fd(20);

    pthread_attr_t pthread_attr;
    pthread_attr_init(&pthread_attr);
    if (pthread_attr_setdetachstate(&pthread_attr, PTHREAD_CREATE_DETACHED) != 0)
    {
        perror("pthread_attr_setdetachstat error!");
        exit(EXIT_FAILURE);
    }

    pthread_t pid;
    if (pthread_create(&pid, &pthread_attr, tcp_server_pthread, NULL) != 0)
    {
        perror("pthread_create error!");
        exit(EXIT_FAILURE);
    }
    pthread_attr_destroy(&pthread_attr);

    struct sockaddr_in clientAddr;
    socklen_t addrlen = sizeof(clientAddr);
    while (1)
    {
        int newfd = accept(sockfd, (struct sockaddr *)&clientAddr, &addrlen);
        if (newfd < 0)
        {
            perror("accept error: ");
            close(sockfd);
            exit(EXIT_FAILURE);
        }

        out_client_info(clientAddr);

        add_fd(vfd, newfd);
    }

    return 0;
}